<template>
  <a-card :bordered="false">
    <h3>任务管理</h3>
    <MarketingFilter :type="4" ref="filter" @onAddTask="handleAddOrEditTask" @onSearch="onSearch"></MarketingFilter>
    <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane :tab="`全部（${all}）`" key=""> </a-tab-pane>
      <a-tab-pane :tab="`未生效（${notStart}）`" key="2"> </a-tab-pane>
      <a-tab-pane :tab="`生效（${process}）`" key="1"> </a-tab-pane>
      <a-tab-pane :tab="`已结束（${end}）`" key="3"> </a-tab-pane>
    </a-tabs>
    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="taskType" slot-scope="record">
        <span v-if="record.taskType == 1">拉新任务</span>
        <span v-if="record.taskType == 2">发帖任务</span>
        <span v-if="record.taskType == 3">首帖奖励</span>
      </span>
      <span slot="taskTarget" slot-scope="text, record">
        <span v-if="record.taskType == 3">/</span>
        <span v-if="record.taskType != 3">{{record.taskTarget}}</span>
      </span>
      <span slot="startTime" slot-scope="text, record">
        <span v-if="record.taskType == 3">/</span>
        <span v-if="record.taskType != 3">{{record.startTime}}</span>
      </span>
      <span slot="endTime" slot-scope="text, record">
        <span v-if="record.taskType == 3">/</span>
        <span v-if="record.taskType != 3">{{record.endTime}}</span>
      </span>
      <span slot="action" slot-scope="record">
        <a @click="handleTaskDetailsList(record)">明细</a>
        <a-divider type="vertical" />
        <a @click="handleAddOrEditTask(record.id)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确认要删除该任务吗？" ok-text="删除" cancel-text="取消" @confirm="handleDelete(record.id)">
          <a>删除</a>
        </a-popconfirm>
      </span>
    </s-table>
  </a-card>
</template>
<script>
import { taskManagerList, taskManagerCount, taskManagerDelete } from '@/api/micromall/communityMarketing'
import { STable } from '@/views/box/components'
import MarketingFilter from '../../components/MarketingFilter'

const columns = [
  {
    title: '任务类型',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'taskType' }
  },
  {
    title: '状态',
    width: '200px',
    align: 'center',
    dataIndex: 'status'
  },
  {
    title: '任务名称',
    width: '180px',
    align: 'center',
    dataIndex: 'taskName'
  },
  {
    title: '奖励信息',
    width: '380px',
    align: 'center',
    dataIndex: 'awardInfo'
  },
  {
    title: '任务目标',
    width: '280px',
    align: 'center',
    scopedSlots: { customRender: 'taskTarget' }
  },
  {
    title: '任务开始时间',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'startTime' }
  },
  {
    title: '任务结束时间',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'endTime' }
  },
  {
    title: '操作',
    width: '150px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    MarketingFilter,
    STable
  },
  data() {
    return {
      all: 0, 
      process: 0, 
      end: 0, 
      notStart: 0,
      total: 0,
      // taskObject: 3,
      activeKey: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {
        taskObject: '3'
      },

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        this.getCount()
        const data = {
          ...this.queryParam,
          current: parameter.pageNo,
          size: parameter.pageSize,
          status: this.activeKey,
          // taskObject: this.taskObject
        }
        return taskManagerList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {
    
  },
  activated() {
    
  },
  computed: {},
  mounted() {},
  watch: {
    $route(to, from) {
      const whiteList = [
        '/micromall/community/marketingManagement/addOrEditTask/',
      '/micromall/community/marketingManagement/taskDetailsList'
      ]
      const currentPathBase = '/micromall/community/marketingManagement/taskList'
      const currentPath = this.$route.path
      if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
        this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
      } else {
        if (currentPath.includes(currentPathBase)) {
          this.activeKey = ''
          this.tabChange(this.activeKey) // 刷新当前页面
        }
      }
    }
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/micromall/community/marketingManagement/taskList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    // 获取状态数量
    getCount() {
      if (this.requestFlag()) return
      taskManagerCount({taskObject: this.queryParam.taskObject}).then(res => {
        if (res.code === 200) {
         const {all, process, end, notStart} = res.data
          this.all = all
          this.end = end
          this.process = process
          this.notStart = notStart
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 任务明细管理
    handleTaskDetailsList(record){
      const { id, taskType, taskName} = record
      this.$router.push(`/micromall/community/marketingManagement/taskDetailsList/${id}?taskType=${taskType}&taskName=${taskName}`)
    },

    // 新增/编辑任务
    handleAddOrEditTask(v) {
      this.$router.push(`/micromall/community/marketingManagement/addOrEditTask/${v}`)
    },

    
    // 删除
    handleDelete(id){
      taskManagerDelete({id}).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          // this.getCount()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },


    // memberTypeChange(v) {
    //   this.taskObject = v
    //   this.$refs.filter.reset()
    //   this.getCount()
    // },

    // 新增/编辑消息类型
    handleAddMessageType(v) {
      this.$router.push(`/micromall/community/marketingManagement/addOrEditMessageType/${v}`)
    },

    // 消息详情
    handleMessageDetails(v) {
      this.$router.push(`/micromall/community/marketingManagement/messageDetails/${v}`)
    },

    tabChange(activeKey) {
      this.$nextTick(() => {
        this.activeKey = activeKey
        this.$refs.filter.reset()
      })
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    handleSubmitSort() {}
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}

.remarks {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
</style>
